var config = require('../../config.js');
const app = getApp();
Page({
  data:{
    placeOfLoadingMask: 'block', 
    display: "block", 
    flag:0,
    isshowindex: 'none',
    provinceList: [],
    provinceIndex: 0,
    cityList: [],
    cityIndex: 0,
    companyInputValue:""
  },

  onLoad: function (options) {
    this.queryCompanyInfo(this);
    var type = options.type;
    app.checkLogin()
    this.setData({ userInfo: app.userInfo, loginUser: app.loginUser, type: type, flag:0})
    console.info("初始化");
    console.info(app.loginUser);
    console.info(type);
    
  },
  onShow: function () {
    this.setData({ flag: 0 })
  },
  changeProvince: function (e) {
    //e.detail.value中的值是数组的下标
    this.setData({
      provinceIndex: e.detail.value,
      province: this.data.provinceList[e.detail.value].administrativeDivisionName
    })
    getCityList(this.data.provinceList[e.detail.value].administrativeDivisionId, this);
  },
  changeCity: function (e) {
    //e.detail.value中的值是数组的下标
    this.setData({
      cityIndex: e.detail.value,
      city: this.data.cityList[e.detail.value].administrativeDivisionName
    })
    getCityList(this.data.provinceIndex, this);
  },

  queryCompanyInfo: function (th) {
    var that = this;
    wx.request({
      url: config.requestUrl + "company/selectCompanyList",
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (msg) {
        console.info("获取全部公司信息");
        console.info(msg);
        wx.hideLoading()
        if (msg.data.msg != null && msg.data.msg == "成功") {
          that.setData({
            allCompanyInfoList: msg.data.content
          })
          getProvinceList(th);
        } else {
          app.tip(msg.data.msg, "none");
          return;
        }
      },
      fail: function (msg) {
        wx.showModal({
          title: '提示',
          content: msg.data.msg,
          showCancel: false
        })
      }
    })
  },
  companyChange: function (e) {
    //文本框的值
    var name = app.trim(e.detail.value);
    var that = this;
    that.setData({
      companyInputValue: name,
    })
    that.doSearch();
  }, 
  doChoose(e) {
    // wx.showLoading({
    //   title: '加载中',
    //   mask: true
    // })
    var that = this;
    console.info("点击标志");
    console.info(that.data.flag);
    if (that.data.flag!=0){
      return false;
    }

    if (that.data.type=="order"){
      if ("1" == e.currentTarget.dataset.makeorderflag){
        var latitude = "";
        var longitude = "";
        if (app.latitude != undefined && app.latitude != null && app.latitude != "") {
          latitude = app.latitude;
        }
        if (app.longitude != undefined && app.longitude != null && app.longitude != "") {
          longitude = app.longitude;
        }

        wx.request({
          url: config.publicBasicinfoUrl,
          method: 'POST',
          header: {
            "content-type": "application/x-www-form-urlencoded"
          },
          data: {
            "userId": app.loginUser.id,
            "tenantCode": e.currentTarget.dataset.index,
            //"tenantId": e.currentTarget.dataset.tenant,
            "latitude": latitude,
            "longitude": longitude
          },
          success: function (result) {
            console.info("获取公版公司基本信息")
            console.info(result);
            var data = result.data;
            if (data.success) {
              app.setCompanyInfo(data.company)
            } else {
              app.tip(data.msg, 'none')
            }
            wx.navigateTo({ url: "../order/order?tenantCode=" + e.currentTarget.dataset.index });
          },
          fail: function ({ errMsg }) {
          },
        })
        
      } else {
        app.tip("对不起，您选择公司没有此功能","none");
        return false ;
      }
    } else if (that.data.type == "deliveryCollection"){
      wx.navigateTo({ url: "../deliveryCollection/deliveryCollection?tenantCode=" + e.currentTarget.dataset.index });
    } else if (that.data.type == "withdraw") {
      
      if (e.currentTarget.dataset.withdrawflag != 1) {
        app.tip("请联系管理员修改取款状态", "none");
        return false;
      }
      
      var latitude = "";
      var longitude = "";
      if (app.latitude != undefined && app.latitude != null && app.latitude != "") {
        latitude = app.latitude;
      }
      if (app.longitude != undefined && app.longitude != null && app.longitude != "") {
        longitude = app.longitude;
      }

      wx.request({
        url: config.publicBasicinfoUrl,
        method: 'POST',
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        data: {
          "userId": app.loginUser.id,
          "tenantCode": e.currentTarget.dataset.index,
          //"tenantId": e.currentTarget.dataset.tenant,
          "latitude": latitude,
          "longitude": longitude
        },
        success: function (result) {
          console.info("取款之后付公司信息的值")
          console.info(result);
          var data = result.data;
          if (data.success) {
            console.info("公司信息重新赋值")
            console.info(data.company)
            app.setCompanyInfo(data.company)
            console.info(app.companyInfo)
          } else {
            app.tip(data.msg, 'none')
          }
          
          wx.request({
            url: config.requestUrl + "/user/getVipInfo",
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
              "id": app.loginUser.id
            },
            success: function (res) {
              wx.hideLoading()
              if (res.data.code == "100") {

                var vipUser = res.data.content;

                //重新设置登录用户信息
                app.setLoginUser(vipUser);
                var auditStatus = vipUser.auditStatus;
                var bankList = vipUser.bankList;
                if (bankList != null && bankList.length > 0) {
                  for (var i = 0; i < bankList.length; i++) {
                    if (app.companyInfo.businessSetting.sameAsDefaultDankFlag) {
                      if (bankList[i].name != app.companyInfo.businessSetting.defaultBank) {
                        app.tip("您未绑定" + app.companyInfo.businessSetting.defaultBank + "呢！", "none");
                        return false;
                      }
                    }
                  }
                }
                if (bankList == null || bankList.length == 0) {
                  wx.showModal({
                    title: '提示',
                    content: '还没有绑定银行卡呢！请添加银行卡！',
                    success: function (res) {
                      if (res.confirm) {
                        wx.navigateTo({ url: "../user/addbank/addbank" })
                      }
                    }
                  })
                } else {
                  console.info("跳转取款界面")
                  wx.navigateTo({ url: "../handheldWithdrawals/withdrawalList/withdrawalList?tenantCode=" + e.currentTarget.dataset.index })
                }
              }
            },
            fail: function ({ errMsg }) {
              app.tip(errMsg, "none");
            }
          })

        },
        fail: function ({ errMsg }) {
          app.tip(errMsg,"none");
        },
        complete: function () {
          
        },
      })
    } else if (that.data.type == "chajian") {
      wx.navigateTo({ url: "../freightTrack/freightTrack?tenantCode=" + e.currentTarget.dataset.index + "&tenantName=" + e.currentTarget.dataset.name });
    } else if (that.data.type == "company") {

      var latitude = "";
      var longitude = "";
      if (app.latitude != undefined && app.latitude != null && app.latitude != "") {
        latitude = app.latitude;
      }
      if (app.longitude != undefined && app.longitude != null && app.longitude != "") {
        longitude = app.longitude;
      }

      wx.request({
        url: config.publicBasicinfoUrl,
        method: 'POST',
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        data: {
          "userId": app.loginUser.id,
          "tenantCode": e.currentTarget.dataset.index,
          //"tenantId": e.currentTarget.dataset.tenant,
          "latitude": latitude,
          "longitude": longitude
        },
        success: function (result) {
          console.info("获取公版公司基本信息")
          console.info(result);
          var data = result.data;
          app.setCompanyInfo(data.company);
          if (!data.success) {
            app.tip(data.msg, 'none')
          }
          wx.navigateTo({ url: "../company/company" });
        },
        fail: function ({ errMsg }) {
        },
      })

      
    } 
    //wx.hideLoading();
    that.setData({
      flag: 1
    })
  },
  doSearch:function (e) {
    var that = this;
    //文本框的值
    var province = app.trim(that.data.province);
    var city = app.trim(that.data.city);
    var name = app.trim(that.data.companyInputValue);
    var arrayObj = new Array();
    var that = this;
    var arr = that.data.allCompanyInfoList;
    console.info(arr);
    if (province.length > 0) {
      if (province=="全部"){
        if (name.length > 0) {
          for (var i = 0; i < arr.length; i++) {
            console.info(arr[i].name);
            if (arr[i].name.indexOf(name) >= 0) {
              arrayObj.push(arr[i]);
            }
          }
        } else {
          arrayObj = that.data.allCompanyInfoList;
        }
      } else {
        if (name.length > 0) {
          for (var i = 0; i < arr.length; i++) {
            console.info(arr[i].name);
            if (arr[i].name.indexOf(name) >= 0 && province == arr[i].province && city == arr[i].city) {
              arrayObj.push(arr[i]);
            }
          }
        } else {
          for (var i = 0; i < arr.length; i++) {
            if (province == arr[i].province && city == arr[i].city) {
              arrayObj.push(arr[i]);
            }
          }
        }
      }
    }
    console.log("==============================================");
    that.setData({
      selCompanyInfoList: arrayObj
    })

  }, 
})


//省选择器的数据加载
function getProvinceList(that) {
  wx.showLoading({
    title: '加载中',
    mask: true
  })
  wx.request({
    url: config.requestUrl + "administrativeDivision/getProvinceAllList",
    method: "POST",
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    success: function (res) {
      wx.hideLoading()

      var data = res.data;
      if (data && data.code && data.code == 100) {
        var provinceLists = data.content;
        console.log(provinceLists)
        if (app.currentPosition != null && app.currentPosition != "" && that.data.province == undefined) {
          that.setData({ provinceList: provinceLists, province: app.currentPosition.address_component.province })
          var administrativeDivisionId = ""
          for (var i = 0; i < provinceLists.length;i++){
            if (app.currentPosition.address_component.province == provinceLists[i].administrativeDivisionName){
              administrativeDivisionId = provinceLists[i].administrativeDivisionId
            }
          }
          getCityList(administrativeDivisionId, that);
        } else {
          that.setData({ provinceList: provinceLists, province: provinceLists[0].administrativeDivisionName })
          getCityList(provinceLists[0].administrativeDivisionId, that);
        }
      } else {
        var errMsg;
        if (data && data.msg) {
          errMsg = data.msg
        } else {
          errMsg = res.statusCode + ":" + res.errMsg
        }
        app.tip(errMsg, 'none')
      }
    },
    fail: function ({ errMsg }) {
      wx.hideLoading()
      app.tip(errMsg, 'none')
    }
  })
}

//市选择器的数据加载
function getCityList(provinceId, that) {

  wx.showLoading({
    title: '加载中',
    mask: true
  })
  wx.request({
    url: config.requestUrl + "administrativeDivision/getCityAllList",
    method: "POST",
    data: {
      "provinceId": provinceId
    },
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    success: function (res) {
      wx.hideLoading() 

      var data = res.data;
      if (data && data.code && data.code == 100) {
        var cityLists = data.content;
        console.log(that.data.city)
        console.log(app.loginUser)
        //if (app.loginUser.city != null && app.loginUser.city != "" && that.data.city == undefined) {
        if (app.currentPosition != null && app.currentPosition != "" && that.data.city == undefined) {
            console.info(11111111111111111111);
            console.info(app.currentPosition);
            console.info(app.currentPosition.address_component.city);
            var areaCode = app.currentPosition.ad_info.city_code.substr(3, app.currentPosition.ad_info.city_code.length);
            console.info(areaCode);
            that.setData({ cityList: cityLists, city: app.currentPosition.address_component.city, areaCode: areaCode })
        } else {
          console.info("初始化市的值");
          console.info(cityLists[0].administrativeDivisionCode);
          that.setData({ cityList: cityLists, city: cityLists[0].administrativeDivisionName, areaCode: cityLists[0].administrativeDivisionCode })
        }

      } else {
        var errMsg;
        if (data && data.msg) {
          errMsg = data.msg
        } else {
          errMsg = res.statusCode + ":" + res.errMsg
        }
        app.tip(errMsg, 'none')
      }
    },
    fail: function ({ errMsg }) {
      wx.hideLoading()
      app.tip(errMsg, 'none')
    },
    complete: function () {
      console.info("改变地区之后的公司");
      console.info(that.data.allCompanyInfoList);
      that.doSearch();
    }
  })
}